<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, reactive } from 'vue';
import * as echarts from 'echarts';
import 'echarts-gl';

const chartRef = ref(null);
let chartInstance = null;

// 图表数据
const chartData = ref([
  { value: 335, name: '直接访问' },
  { value: 310, name: '邮件营销' },
  { value: 234, name: '联盟广告' },
  { value: 135, name: '视频广告' },
  { value: 1548, name: '搜索引擎' }
]);

const initChart = () => {
  if (!chartRef.value) return;
  
  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  
  // 初始化新实例
  chartInstance = echarts.init(chartRef.value);
  
  // 3D饼图配置
  const option = {
    title: {
      text: '访问来源分析',
      left: 'center',
      textStyle: {
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: chartData.value.map(item => item.name)
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '60%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        // 3D效果配置
        roseType: 'radius',
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx) {
          return Math.random() * 200;
        },
        // 使用echarts-gl的3D效果
        itemStyle: {
          opacity: 0.8, // 透明度
          shadowBlur: 20,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        // 3D饼图特有的深度配置
        depth: 50, // 饼图厚度
        stillShowZeroSum: false,
        data: chartData.value
      }
    ]
  };
  
  // 设置图表选项
  chartInstance.setOption(option);
};

onMounted(() => {
  nextTick(() => {
    initChart();
    
    // 监听窗口大小变化，调整图表
    window.addEventListener('resize', handleResize);
  });
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  
  window.removeEventListener('resize', handleResize);
});

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>    